# Configuration - AWS base image
variable "base_ami" {
  type    = string
  default = "ami-0851b76e8b1bce90b"
}

# Configuration - AWS provisioning instance type
variable "instance_type" {
  type    = string
  default = "t2.micro"
}

# Configuration - AWS subnet
variable "subnet_id" {
  type    = string
  default = ""
}

# Configuration - AWS VPC
variable "vpc_id" {
  type    = string
  default = ""
}

# Configuration - DO token
variable "token" {
  type    = string
  default = "${env("DIGITALOCEAN_TOKEN")}"
}


# "timestamp" template function replacement
locals { timestamp = regex_replace(timestamp(), "[- TZ:]", "") }

# Variable - AMI naming
locals {
  ami_name   = "appsmith-ami-${local.timestamp}"
  image_name = "appsmith-marketplace-snapshot-${local.timestamp}"
}

# Builder - Provision AWS instance
source "amazon-ebs" "autogenerated_1" {
  ami_name      = "${local.ami_name}"
  instance_type = "${var.instance_type}"
  launch_block_device_mappings {
    delete_on_termination = true
    device_name           = "/dev/sda1"
    volume_size           = 15
    volume_type           = "gp2"
  }
  region          = "ap-south-1"
  source_ami      = "${var.base_ami}"
  ssh_username    = "appsmith"
  subnet_id       = "${var.subnet_id}"
  vpc_id          = "${var.vpc_id}"
  skip_create_ami = false
  user_data_file  = "./defaults.cfg"
}

# Builder - Provision DO droplet
source "digitalocean" "autogenerated_2" {
  api_token      = "${var.token}"
  image          = "ubuntu-20-04-x64"
  region         = "blr1"
  size           = "s-1vcpu-1gb"
  snapshot_name  = "${local.image_name}"
  ssh_username   = "appsmith"
  user_data_file = "./defaults.cfg"
}

# Provisioning - Setup Appsmith
build {
  sources = ["source.amazon-ebs.autogenerated_1", "source.digitalocean.autogenerated_2"]

  provisioner "ansible" {
    extra_arguments = ["--tags", "packer"]
    user = "appsmith"
    playbook_file = "../ansible/appsmith_playbook/appsmith-playbook.yml"
  }

  provisioner "ansible" {
    only = ["amazon-ebs.autogenerated_1"]
    user = "appsmith"
    extra_arguments = ["--tags", "packer-aws", "--skip-tags", "always"]
    playbook_file = "../ansible/appsmith_playbook/appsmith-playbook.yml"
  }
}
